﻿using System;
using System.Linq;
using QAS.Nekorama.Models;

namespace QAS.Nekorama.Functions
{
    public class QuestionFunction
    {
        public static IQueryable<Question> SearchQuestions(string searchString)
        {
            var db = new Entities();
            IQueryable<Question> questionList = from q in db.Questions
                select q;
            if (searchString.StartsWith("#")) //search by tag
            {
                searchString = searchString.Substring(1);
                string tagKey = searchString.Split(':')[0];
                if (searchString.Contains(':')) //search full text with tag
                {
                    string textKey = searchString.Substring((tagKey.Length + 1)).Trim();
                    //substring from length of #tagname                
                    if (!String.IsNullOrEmpty(textKey))
                    {
                        questionList = from q in db.Questions
                            join fts in db.QuestionSearch(textKey)
                                on q.QuestionID equals fts.KEY
                            select q;
                    }
                }
                questionList = questionList.Where(q => q.TagName1.Equals(tagKey)
                                                       || q.TagName2.Equals(tagKey)
                                                       || q.TagName3.Equals(tagKey)
                                                       || q.TagName4.Equals(tagKey)
                                                       || q.TagName5.Equals(tagKey));
            }
            else //search full text
            {
                questionList = from q in db.Questions
                    join fts in db.QuestionSearch(searchString)
                        on q.QuestionID equals fts.KEY
                    select q;
            }
            return questionList;
        }

        
    }
}